package com.tre.jdevtemplateboot.common.util;

import org.jsoup.Jsoup;
//jsoup 1.15.3版本Whitelist已更新为Safelist类。老版本的Whitelist已删除
import org.jsoup.safety.Safelist;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XSSWhiteListUtils {

    private static Map<String, Safelist> whitelist = new HashMap<>();

    private XSSWhiteListUtils(){
        throw new IllegalStateException("Utility class");
    }

    static {
        whitelist.put("none", Safelist.none());
        whitelist.put("relaxed", Safelist.relaxed());
        whitelist.put("basic", Safelist.basic());
        whitelist.put("simpleText", Safelist.simpleText());
        whitelist.put("basicWithImages", Safelist.basicWithImages());
    }

    private static Safelist whiteListType() {
        String whiteList = YamlConfigurerUtil.getStrYmlVal("xss.white-list");
        Iterator<Map.Entry<String, Safelist>> entryIterator = whitelist.entrySet().iterator();
        while (entryIterator.hasNext()) {
            Map.Entry<String, Safelist> entry = entryIterator.next();
            if (entry.getKey().equalsIgnoreCase(whiteList)) {
                return entry.getValue();
            }
        }
        return Safelist.none();
    }

    public static String clean(String bodyHtml) {
        return Jsoup.clean(bodyHtml, whiteListType());
    }

}
